import datetime
import time

import requests,json

from db import db
from utils.myredis import r
from views.base import BaseHandler
from utils.comm import gettoken

class Setinvest(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        userid = int(data["userid"])
        bdid =int(data["code"])
        sql = """select * from invest where bdid=%d""" % (int(bdid))
        land = db.findone(sql)
        key = 'bid'
        times = time.time() + 20
        if not land:
            r.sortedset_add(key, bdid, times)
        money = int(data["money"])
        create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        # 利息
        lx = data["lx"]
        lx1 = lx / 100
        accrual = money * lx1
        # 总金额
        cmoney = money + accrual
        print(userid)
        sql2 = "select money from user where id=%d"%(userid)
        res = db.findone(sql2)
        print(res)
        if money <= int(res["money"]):
            try:
                # 写入投资表
                sql = "insert into invest(userid, bdid, money, create_time, accrual, cmoney) values (%d,%d,'%s','%s','%s','%s')"%(userid,bdid,money,create_time,accrual,cmoney)
                db.add(sql)
                # 跟新标的表中的剩余金额
                number = hash(bdid) % 3
                if number == 0:
                    sql3 = "update landmarks set money=money-%d where code=%d"%(money,bdid)
                    db.add(sql3)
                else:
                    landmarks = "landmarks" + str(number)
                    sql4 = "update %s set money=money-%d where code=%d"%(landmarks,money,bdid)
                    db.add(sql4)
                # 跟新投资人总金额以及锁定金额
                smoney = int(res["money"]) - money
                sql5 = "update user set money=%d,locks=locks+%d where id=%d"%(smoney,money,userid)
                db.add(sql5)
                db.commit()
                return self.finish({"code": 200, "msg": "投资成功"})
            except Exception as a:
                db.rollback()
                print(a)
                return self.finish({"code": 400, "msg": "投资失败"})
        else:
            return self.finish({"code": 400, "msg":"金额不足"})



